<template>
    <div class="user-center">
        <a-row class="table-up-row">
            <span>
                {{ route.name === 'edit-password' ? '修改密码' : '重置密码' }}
            </span>
        </a-row>

        <a-row>
            <a-col :span="12" :offset="4">
                <a-form
                    ref="formRef"
                    :model="formState"
                    :label-col="{ span: 8 }"
                    :wrapper-col="{ span: 16 }"
                    autocomplete="off"
                    :rules="rules"
                >
                    <template v-if="route.name === 'edit-info'">
                        <a-form-item label="用户头像">
                            <a-row v-if="formState.imageUrl" align="middle">
                                <a-image
                                    style="width: 150px; max-height: 100%"
                                    :src="formState.imageUrl"
                                    alt="avatar"
                                />
                                <a-button style="margin-left: 10px" @click="formState.imageUrl = ''"
                                    >更换头像</a-button
                                >
                            </a-row>
                            <a-upload
                                v-else
                                v-model:file-list="fileList"
                                list-type="picture-card"
                                class="avatar-uploader"
                                :show-upload-list="false"
                                :before-upload="beforeUpload"
                            >
                                <div>
                                    <loading-outlined v-if="loading"></loading-outlined>
                                    <plus-outlined v-else></plus-outlined>
                                    <div class="ant-upload-text" v-else>点击上传</div>
                                </div>
                            </a-upload>
                        </a-form-item>

                        <a-form-item label="昵称" name="nickName">
                            <a-input v-model:value="formState.nickName" />
                        </a-form-item>
                        <a-form-item label="用户名" name="userName">
                            <a-input v-model:value="formState.userName" />
                        </a-form-item>
                        <a-form-item label="手机号" name="phone">
                            <a-input v-model:value="formState.phone" />
                        </a-form-item>
                        <a-form-item label="年龄" name="age">
                            <a-input-number
                                style="width: 100%"
                                min="18"
                                :keyboard="true"
                                v-model:value="formState.age"
                            />
                        </a-form-item>
                        <a-form-item label="性别" name="gender">
                            <a-select style="width: 100%" v-model:value="formState.gender">
                                <a-select-option :value="1">男</a-select-option>
                                <a-select-option :value="0">女</a-select-option>
                            </a-select>
                        </a-form-item>
                    </template>

                    <a-form-item label="原密码" name="password" v-if="route.name != 'edit-info'">
                        <a-input-password v-model:value="formState.password" />
                    </a-form-item>

                    <template v-if="route.name === 'edit-password'">
                        <a-form-item label="新密码" name="newPassword">
                            <a-input-password v-model:value="formState.newPassword" />
                        </a-form-item>

                        <a-form-item label="确认密码" name="rePassword">
                            <a-input-password v-model:value="formState.rePassword" />
                        </a-form-item>
                    </template>

                    <a-form-item :wrapper-col="{ offset: 8, span: 24 }">
                        <a-button type="primary" @click="submit" size="large" style="width: 100%"
                            >确认</a-button
                        >
                    </a-form-item>
                </a-form>
            </a-col>
            <a-col :span="6"></a-col>
        </a-row>

        <a-row v-if="route.name === 'reset-password'" style="color: #aaaaaa">
            请输入原密码进行验证，进而才能重置
        </a-row>
    </div>
</template>
<script lang="ts">
import { defineComponent, reactive, toRefs, ref, onMounted } from 'vue'
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue'
import { useRoute, useRouter } from 'vue-router'
import Lodash from 'lodash'

import { changePwd, editInfo, uploadImg } from './store'
import { toast } from '@/utils/common'
import { getLocal } from '@/utils/localStorage'
import useMainStore from '@/stores'

const defaultFormState = {
    id: '',
    userName: '',
    password: '',
    newPassword: '',
    nickName: '',
    age: '',
    gender: '',
    imageUrl: ''
}
export default defineComponent({
    name: 'userCenter',
    components: {
        PlusOutlined,
        LoadingOutlined
    },
    setup() {
        const { getUserInfo } = useMainStore().useUserStore()
        const route = useRoute()
        const router = useRouter()
        const components = {
            formRef: ref() as any
        }
        const constant = {
            rules: {} as any
        }
        for (let key in defaultFormState) {
            constant.rules[key] = [{ required: true, message: '请输入！' }]
        }

        const state = reactive({
            formState: Lodash.cloneDeep(defaultFormState),
            fileList: [] as Array<any>,
            loading: false
        })

        onMounted(() => {
            getUserInfo(getLocal('token'))
            const { nickName, age, gender, phone, imageUrl, userName, id } = getLocal('userInfo')
            state.formState = {
                ...state.formState,
                id,
                nickName,
                age,
                gender,
                phone,
                imageUrl,
                userName
            }
        })
        const methods = {
            async submit() {
                if (
                    state.formState.newPassword &&
                    state.formState.newPassword !== state.formState.rePassword
                ) {
                    toast('error', '', '两次密码不一致！')
                    return
                }
                await components.formRef.value.validateFields()
                const params = Lodash.cloneDeep(state.formState)
                //删除脏数据
                if (route.name === 'reset-password') {
                    params.newPassword = '123'
                }
                if (route.name === 'edit-info') {
                    delete params.newPassword
                    delete params.rePassword
                }
                if (route.name !== 'edit-info') {
                    delete params.nickName
                    delete params.gender
                    delete params.age
                }

                delete params.rePassword
                const fetchStore = route.name === 'edit-info' ? editInfo : changePwd
                try {
                    const res: any = await fetchStore(params)
                    if (res.status === 200) {
                        toast()
                    } else {
                        toast('error', '', res.result.msg)
                    }
                    if (route.name !== 'edit-info') {
                        components.formRef.value.resetFields()
                    } else {
                        let token = getLocal('token')
                        try {
                            getUserInfo(token)
                        } catch (e) {
                            router.push('/login')
                        }
                    }
                } catch (e: any) {
                    console.log(e)
                }
            },
            async beforeUpload(file: any) {
                state.loading = true
                const formdata = new FormData()
                formdata.append('image', file)
                try {
                    const res = await uploadImg(formdata)
                    state.formState.imageUrl = res.imageUrl
                } catch (err) {
                    console.log(err)
                } finally {
                    state.loading = false
                }
                return false
            }
        }
        return {
            ...toRefs(state),
            ...constant,
            ...methods,
            ...components,
            route
        }
    }
})
</script>
<style lang="scss" scoped>
.user-center {
    width: 100%;
    height: 100% !important;
    background-color: #ffffff;
    padding: 20px;
    .table-up-row {
        margin-bottom: 50px;
    }
}
</style>
